package com.wxx;

/**
 * @author: Jetwang
 * @date: 2022/3/17 19:33
 * @description: GenericLinearSearch 将数据类型设置为泛型
 * @version: 1.0
 */
public class GenericLinearSearch {

    /**
     * 将构造器私有
     */
    private GenericLinearSearch() { }

    /**
     * 线性查找
     * @param data 数组
     * @param target 目标值
     * @return
     */
    public static <T> int search(T[] data, T target) {
        for (int i = 0; i < data.length; i++) {
            if (target.equals(data[i])) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Integer[] arr = {1, 2, 4, 6, 3};
        int index = GenericLinearSearch.search(arr, 6);
        System.out.println(index);

        Character[] chars = {'a', 'd', 'r', 'g', 'e'};
        int index02 = GenericLinearSearch.search(chars, 'd');
        System.out.println(index02);

        String[] strs = {"aaa", "bbb", "ttt", "sss", "fff"};
        int index03 = GenericLinearSearch.search(strs, "fff");
        System.out.println(index03);

        Student student01 = new Student("Jet");
        Student student02 = new Student("Jerry");
        Student student03 = new Student("Jack");
        Student student04 = new Student("Jackson");

        Student[] students = {student01, student02, student03, student04};
        int index04 = GenericLinearSearch.search(students, new Student("jack"));
        System.out.println(index04);

        long startTime = System.nanoTime();
        Integer[] newArr = ArrayGenerator.generateOrderedArray(10000000);
        long endTime = System.nanoTime();
        int index05 = GenericLinearSearch.search(newArr, 666);
        System.out.println(index05);
        double time = (endTime - startTime) / 1000000000.0;
        System.out.println(time + "s");
    }
}
